import requests
import os,sys
from bs4 import BeautifulSoup
import threading
import re
import json
import time

TSBASE = "H:/TS"
MP4BASE = "H:/mp4"
user = os.getlogin()
userHome = "C:/Users/{}".format(user)
logPath = "{}/Desktop/logs".format(userHome)

myHeaders = {
    "User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36 Edg/120.0.0.0"
}
requests.packages.urllib3.disable_warnings()




def NowDate(format_str = "%Y-%m-%d %H:%M:%S"):
    return time.strftime(format_str,time.localtime())

def TryRun(func):
    import functools
    defName = getMyName()
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        try:
            res = func(*args, **kwargs)
            return res
        except Exception as e: 
            except_type, except_value, except_traceback = sys.exc_info()
            log.error("{} 执行失败 {} ".format(func.__name__,e.__dict__.get("msg")))
            # log.error("{0} {1}方法执行失败， 原因 {2}".format(defName ,func.__name__,e))
            return None
    return wrapper

def getMyName(callback = False,Line = False):
    frameInfo = sys._getframe(1)
    lineNum = frameInfo.f_lineno
    if callback:
        return frameInfo.f_back.f_code.co_name,lineNum
    return [frameInfo.f_code.co_name,frameInfo.f_back.f_code.co_name,lineNum]

def CheckFolder(filepath):
    if os.path.exists(filepath):
        return
    else:
        os.makedirs(filepath)

class Log():
    def __init__(self,logName = "",Echo = True):
        self.logName = logName
        self.Echo = Echo
        CheckFolder(logPath)
    @TryRun
    def WriteMsg(self,msg):
        now_date = NowDate(format_str = "%Y%m%d%H")
        with open("{}/{}{}.log".format(logPath,self.logName,now_date),"a",encoding = "utf-8") as f:
            f.write(msg)
            f.close()

    def info(self,*args):
        frameInfo = sys._getframe(1)
        lineNum = frameInfo.f_lineno
        funcname = frameInfo.f_back.f_code.co_name
        now_date = NowDate()
        msg = now_date+" INFO {0} {1}行 ".format(funcname,lineNum )
        for m in args :
            msg += " {}".format(m)
            
        msg +="\n"
        if self.Echo:
            print(msg)
        self.WriteMsg(msg)

    def error(self,*args):
        funcname ,line = getMyName(callback = True)
        now_date = NowDate()
        msg = now_date+" error {0} {1}行 ".format(funcname,line )
        for m in args :
            msg += " "
            msg += m
        msg +="\n"
        if self.Echo:
            print(msg)
        self.WriteMsg(msg)

    def warning(self,*args):
        funcname ,line = getMyName(callback = True)
        now_date = NowDate()
        msg = now_date+" warning {0} {1}行 ".format(funcname,line )
        for m in args :
            msg += " "
            msg += m
        msg +="\n"
        if self.Echo:
            print(msg)
        self.WriteMsg(msg)


log = Log(logName = "movie_run")


def compress_mp4(input_file, output_file):
    from moviepy.editor import VideoFileClip
    clip = VideoFileClip(input_file)
    # 设置输出参数（比特率、分辨率等）
    print(clip.size)
    clip.write_videofile(output_file, codec='libx264')

def download_m3u8_video(url, file_path):
    if os.path.exists(file_path):
        return True
    r = requests.get(url)
    if r.status_code != 200:
        log.error('m3u8视频下载链接无效')
        return False

    m3u8_list = r.text.split('\n')
    m3u8_list = [i for i in m3u8_list if i and i[0] != '#']
    ts_list = []

    for ts_url in m3u8_list:
        ts_url = url.rsplit('/', 1)[0] + '/' + ts_url
        ts_list.append(ts_url)
    thread_list = []

    with open(file_path, 'wb') as f:
        for ts_url in ts_list:
            def WriteTs(tryNum = 0):
                if tryNum > 3:
                    log.warning("重试3次失败")
                    return False
                log.info("共{}个ts，开始下载 {}".format(len(ts_list),ts_url))
                tryNum +=1
                ts_url1 = ts_url
                try:
                    if ts_url.count("https") > 1:
                        ts_url1 = "https://"+ ts_url.split("https://")[-1]
                        
                    r = requests.get(ts_url1,verify=False,headers = myHeaders,allow_redirects=True)
                    if r.status_code == 200:
                        log.info("资源大小 ",len(r.content))
                        f.write(r.content)
                    else:
                        log.error("数据错误，返回 ",str(r.status_code))
                    return True
                except Exception as e:
                    log.error(e)
                    return WriteTs()

            WriteTs()
            # if len(thread_list) < 10:
            #     t = threading.Thread(target = WriteTs)
            #     t.start()
            #     thread_list.append(t)
            # else:
            #     for t in thread_list:
            #         print(len(thread_list))
            #         t.join()
            #     thread_list = []



    log.info('m3u8视频下载完成')
    return True

def convert_ts_to_mp4(ts_file_path, mp4_file_path):
    cmdStr = f'ffmpeg -i {ts_file_path} -c copy {mp4_file_path}'
    # os.system()
    print(cmdStr)


def GetTSSource():
    for i in range(1,100):
        # http://fnyy.shop/vodplay/144079-1-1.html 182781 337167
        web_url = "http://fnyy.shop/vodplay/337167-3-{}.html".format(i)
        res = requests.get(url = web_url)
        soup = BeautifulSoup(res.text, 'html.parser')
        script_tags = soup.find_all("script")
        sc = script_tags[8]
        tmp = sc.get_text().replace("var player_aaaa=","")
        tv_json = json.loads(tmp)
        ts_url = tv_json.get("url")
        tvName = tv_json.get("vod_data").get("vod_name")
        SavePath =  f'{TSBASE}/{tvName}'.format(TSBASE,tvName)
        CheckFolder(SavePath)
        log.info("开始下载{}第{}集".format(tvName,i))
        ts_file_path = f'{SavePath}/第{i}集.MP4'.format(SavePath,tv_json.get("nid"))
        
        download_m3u8_video(ts_url, ts_file_path)

def Run():
    tvName = "渗透"
    SavePath =  f'{TSBASE}/{tvName}'.format(TSBASE,tvName)
    CheckFolder(SavePath)
    for i in range(1,41):
        if i < 10:
            # url = 'https://s6.bfzycdn.com/video/dazhaimen2/第0{}集/index.m3u8'.format(i)
            url = 'https://s1.bfzycdn.com/video/shentou/第0{}集/index.m3u8'.format(i)
            # https://v.gsuus.com/play/Le3m3Lnb/index.m3u8
        else:
            # url = 'https://s6.bfzycdn.com/video/dazhaimen2/第{}集/index.m3u8'.format(i)
            url = 'https://s1.bfzycdn.com/video/shentou/第{}集/index.m3u8'.format(i)
        log.info(url)
        ts_file_path = f'{SavePath}/第{i}集.MP4'.format(SavePath,i)
        download_m3u8_video(url, ts_file_path)

        # mp4_file_path = f'{MP4BASE}/第{i}集.mp4'.format(MP4BASE,i)
        # CheckFolder(MP4BASE)
        # convert_ts_to_mp4(ts_file_path, mp4_file_path)
if __name__ == '__main__':
    # GetTSSource()
    input_file, output_file = "H:/TS/xdf.mp4","H:/TS/xdfnew.mp4"
    convert_ts_to_mp4(input_file, output_file)